package org.example;

public abstract class Parser {
    protected final Lexer input; // 词法解析器
    protected final Token[] lookahead;
    protected final int k; // 向前看符号的个数
    protected int p; // 当前缓冲区中装填下一个词法单元的位置

    public Parser(Lexer input, int k) {
        this.input = input;
        this.k = k;
        p = 0;
        lookahead = new Token[k];
        for (var i = 0; i < k; i++) {
            consume();
        }
    }

    // 返回向前看的第i个词法单元（i从1开始）
    public Token LT(int i) {
        return lookahead[(p + i - 1) % k];
    }

    // 返回向前看第i给词法单元的类型
    public int LA(int i) {
        return LT(i).type;
    }

    public void match(int type) {
        if (LA(1) == type) {
            consume();
        } else {
            throw new Error("期望:" + input.getTokenName(type) + ", 实际:" + LT(1));
        }
    }

    public void consume() {
        lookahead[p] = input.nextToken();
        p = (p + 1) % k;
    }
}
